package cn.tangsihai.hrm.config;

import cn.tangsihai.hrm.mq.MQConsumer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.tangsihai.hrm.mq.MQConsumer.*;

/**
 * RebbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {
    // 创建交换机
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(MQConsumer.EXCHANGE_NAME0).durable(true).build();
    }

    // 创建短信队列
    @Bean
    public Queue SMSQueue(){
        return new Queue(QUEUE_NAME_SMS);
    }
    // 创建邮件队列
    @Bean
    public Queue EmailQueue(){
        return new Queue(QUEUE_NAME_EMAIL);
    }
    // 创建站内信队列
    @Bean
    public Queue MessageQueue(){
        return new Queue(QUEUE_NAME_MESSAGE);
    }

    // 绑定短信队列到交换机
    @Bean
    public Binding SMSBinding(){
        return BindingBuilder.bind(SMSQueue()).to(exchange()).with("#.sms").noargs();
    }

    // 绑定邮件队列到交换机
    @Bean
    public Binding EmailBinding(){
        return BindingBuilder.bind(EmailQueue()).to(exchange()).with("#.email").noargs();
    }

    // 绑定站内信队列到交换机
    @Bean
    public Binding MessageBinding(){
        return BindingBuilder.bind(MessageQueue()).to(exchange()).with("#.message").noargs();
    }

    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
}
